ai = {}

 local dirs = {{x = 0 , y = -1},{x = 0 , y = 1},{ x = 1 , y = 0 },{x = -1, y = 0},{x=0, y = 0 }}
 local goToPlayerBias = 3
 
function ai:setState(s)
  self.state = s
end

function ai:init(m, u, p)
  math.randomseed(os.clock())
  self.sameDirCount = 0
  self.map = m
  self.unit = u
  self.player = p
  self.grid = Grid(m)
  self.goto = dirs[5] -- set to no dir
  self:setState("search")
end

function ai:updateState(dt)
  if self.state == "search" then
    self.sameDirCount = self.sameDirCount + dt
    self:search()
  elseif self.state == "kill" then
  else
    self:setState("wait")
  end
end


function ai:search()
  --add chance to suddenly pick a new dir, based on how long been goin in the same
  local chance = math.max(25, 300 - self.sameDirCount * 10)
  local new = math.random(chance) == 1
  
  --got direction?
  if self.goto == dirs[5] or not self:neighborWalkable(self.goto) or new then
    
    --reset directions.
    ai.unit.move.u = false
    ai.unit.move.d = false
    ai.unit.move.l = false
    ai.unit.move.r = false
    
    --find new random direction
    self:rndGoto()  
  else
    self:move()
  end  
end

function ai:move()
  --set direction according to goto
  --Added in code to flip the draw direction of the enemy depending on the direction they're going
    if self.goto.x < 0 then
      self.unit.drawL = true
      self.unit.move.l = true
      self.unit.move.r = false
    elseif self.goto.x > 0 then
      self.unit.drawL = false
      self.unit.move.l = false
      self.unit.move.r = true
    else
      self.unit.move.l = false
      self.unit.move.r = false
    end
    
    if self.goto.y < 0 then
      self.unit.move.u = true
      self.unit.move.d = false
    elseif self.goto.y > 0 then
      self.unit.move.u = false
      self.unit.move.d = true
    else
      self.unit.move.u = false
      self.unit.move.d = false
    end 
end

function ai:rndGoto()
  local i = math.random(4 + goToPlayerBias)
  
  if i > 4 then
    --refresh player direction
    local pDir = {x = 0, y = 0}
    pDir.x = self.player.pos.gx - self.unit.pos.gx
    pDir.y = self.player.pos.gy - self.unit.pos.gy
    
    if pDir.x > 0 then
      pDir.x = 1
    elseif pDir.x < 0 then
      pDir.x = -1
    end
    
    if pDir.y > 0 then
      pDir.y = 1
    elseif pDir.y < 0 then
      pDir.y = -1
    end
    
    self.goto = pDir
  else
    local free = self:neighborWalkable(dirs[i])
    
    if free and self.goto ~= dirs[i] then 
      self.sameDirCount = 0
      self.goto = dirs[i]
    end
  end
end

function ai:neighborWalkable(dir)  
  return self.map[self.unit.pos.gx + dir.x +1][self.unit.pos.gy + dir.y +1 ] == 0
end


function ai:setUnit(u)
  self.unit = u
end

function ai:update(dt)
  self:updateState(dt)
end


